export function updateDepartmentIds(tree) {
  const userIdCount = {};
  const duplicateUserIds = [];
  const processTree = (nodes) => {
    return nodes.map((node) => {
      const newNode = { ...node };
      if (newNode.organization_type === 1) {
        newNode.id = `d${newNode.id}`;
      }
      if (newNode.organization_type === 2) {
        const originalId = newNode.id;
        userIdCount[originalId] = (userIdCount[originalId] || 0) + 1;
        if (userIdCount[originalId] > 1) {
          newNode.id = `${originalId}_${userIdCount[originalId] - 1}`;
        }
      }
      if (Array.isArray(newNode.sub) && newNode.sub.length > 0) {
        newNode.sub = processTree(newNode.sub);
      }

      return newNode;
    });
  };
  const updatedTree = processTree(tree);
  for (let userId in userIdCount) {
    if (userIdCount[userId] > 1) {
      duplicateUserIds.push({ [userId]: userIdCount[userId] });
    }
  }

  return { updatedTree, duplicateUserIds };
}

export function transformIds(obj, arr) {
  return arr.flatMap((id) => {
    const item = obj.find((o) => o.hasOwnProperty(id));

    if (item) {
      const count = item[id]; 
      return [
        id,
        ...Array.from(
          { length: count - 1 },
          (_, index) => `${id}_${index + 1}`
        ),
      ];
    }
    return [id];
  });
}

export function simplifyIds(arr) {
  const result = []; 
  const seen = new Set();  
  arr.forEach(item => {
    const baseId = item.toString().split('_')[0];
    if (!seen.has(baseId)) {
      result.push(Number(baseId));
      seen.add(baseId);
    }
  });

  return result;
}

export function filterTreeByIds(tree, ids) {
  let result = [];
  tree.forEach((node) => {
    if (ids.includes(node.id)) {
      const filteredNode = {
        id: node.id,
        name: node.name,
        organization_type: node.organization_type,
      };
      if (node.sub) {
        const filteredChildren = filterTreeByIds(node.sub, ids);
        if (filteredChildren.length > 0) {
          filteredNode.sub = filteredChildren;
        }
      }
      result.push(filteredNode);
    } else if (node.sub) {
      const filteredChildren = filterTreeByIds(node.sub, ids);
      if (filteredChildren.length > 0) {
        result = result.concat(filteredChildren); // 平铺符合条件的子节点
      }
    }
  });

  return result;
}


/**
 * 自动补全同组 id（如选中 a_1 补全 a, a_2）
 * @param {Array<Object>} obj - 包含 id 和重复次数的对象数组
 * @param {Array<string>} selected - 当前选中的 id（可能包含 a_1 这种后缀）
 * @returns {Array<string>} - 补全后的 id 列表
 */
export function expandSelectedIds(obj, selected, previous = []) {
  const idMap = new Map();

  obj.forEach((item) => {
    const key = Object.keys(item)[0];
    const count = item[key];
    idMap.set(Number(key), count);
  });

  const toSet = new Set(previous); // 基于上一次构建集合

  const newIds = new Set(selected);
  const oldIds = new Set(previous);

  // 找出新增的 id
  const added = [...newIds].filter((x) => !oldIds.has(x));
  // 找出取消的 id
  const removed = [...oldIds].filter((x) => !newIds.has(x));

  // 处理新增：补全整个组
  added.forEach((rawId) => {
    const baseId = Number(String(rawId).split('_')[0]);
    const count = idMap.get(baseId);
    if (count) {
      for (let i = 0; i < count; i++) {
        toSet.add(i === 0 ? baseId : `${baseId}_${i}`);
      }
    } else {
      toSet.add(rawId);
    }
  });

  // 处理移除：整组移除
  removed.forEach((rawId) => {
    const baseId = Number(String(rawId).split('_')[0]);
    const count = idMap.get(baseId);
    if (count) {
      for (let i = 0; i < count; i++) {
        toSet.delete(i === 0 ? baseId : `${baseId}_${i}`);
      }
    } else {
      toSet.delete(rawId);
    }
  });

  return Array.from(toSet);
}